using System;
using System.Collections.Generic;
using System.IO;

namespace CurrencyConv.Core.SettingsManager
{
	public interface ISettingsManager
	{
		CCSettings LoadSettings();
		CCSettings ForceReload();
		void PersistSettings();
	}

	public class SettingsManager : ISettingsManager
	{
		private CCSettings _loadedSettings;

		public CCSettings LoadSettings()
		{
			if (_loadedSettings != null) return _loadedSettings;

			if (!File.Exists(Consts.SettingsFilePath)) return CCSettings.Default;


			IList<string> lines = ReadAllLines();

			CCSettings settings = new CCSettings
															{
																RemoteSiteAddress = getSetting("RemoteSiteAddress", lines),
																SavedExchangeRatesPath = getSetting("SavedExchangeRatesPath", lines)
															};

			_loadedSettings = settingsAreValid(settings) ? settings : CCSettings.Default;
			return _loadedSettings;
		}

		public CCSettings ForceReload()
		{
			_loadedSettings = null;
			return LoadSettings();
		}

		public void PersistSettings()
		{
			throw new NotImplementedException();
		}

		private bool settingsAreValid(CCSettings settings)
		{
			return settings != null
							&& !string.IsNullOrEmpty(settings.RemoteSiteAddress)
							&& !string.IsNullOrEmpty(settings.SavedExchangeRatesPath);
		}

		private string getSetting(string propertyName, IEnumerable<string> lines)
		{
			foreach (string line in lines)
			{
				string[] split = line.Split(' ');
				if (split.Length != 2) continue;

				if (split[0] == propertyName)
					return split[1];
			}
			return "";
		}

		private IList<string> ReadAllLines()
		{
			IList<string> lines = new List<string>();
			using (FileStream stream = File.OpenRead(Consts.SettingsFilePath))
			{
				using (TextReader reader = new StreamReader(stream))
				{
					string line;
					while ((line = reader.ReadLine()) != null)
					{
						if (line == "\r" || line == "\n" || line == "\r\n" || string.IsNullOrEmpty(line)) continue;

						lines.Add(line);
					}
				}
			}
			return lines;
		}
	}
}